#!/usr/bin/env groovy

import com.Ostermiller.util.CSVParser;
import com.martiansoftware.jsap.*;

//TODO:this is a hack that looks like it's a bug in Groovy -
//a single character in ' ' should evaluate to a char, but it looks like
//it's going to a string - download lastest groovy and check

char n = 'n'
char i = 'i'
FlaggedOption nameOption = new FlaggedOption ("name", 
JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
 n, 'name', "name given to every POI (if not used, then each POI is named after the 3rd item in the file)");

FlaggedOption iconUrlOption = new FlaggedOption ("iconUrl", 
JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, i, 'iconUrl', 
"url of icon for each POI - optional");

UnflaggedOption fileName = new UnflaggedOption( "fileName", 
JSAP.STRING_PARSER, JSAP.NOT_REQUIRED, "Input file name (defaults to stdin)");

SimpleJSAP jsap = new SimpleJSAP(
	"csv2kml",
	"converts CSV file of POIs into a KML file of POIs",
	(Parameter[])[nameOption, iconUrlOption, fileName]

)

JSAPResult config = jsap.parse(args)

def writer = new StringWriter()
def kml = new groovy.xml.MarkupBuilder(writer)

InputStream inFile;
if (config.contains("fileName")) {
	inFile = new File(config.getString("fileName")).newInputStream();
} else {
	inFile = System.in
}

kml.kml(xmlns:"http://earth.google.com/kml/2.1") {
kml.Document() {
	inFile.withReader { reader ->
		CSVParser parser = new CSVParser(reader);
		parser.getAllValues().each { line ->
			kml.Placemark() {
				if (config.contains("name")) {
					name(config.getString("name"))
					description("${line[2]} - ${line[3]}")
				} else {
					name("${line[2]}")
					description("${line[3]}")
				}
				Point() {
					
coordinates("${line[0]},${line[1]}")
				}
			}
		}
	}
}
}
println writer.toString()
